package com.mbw.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mbw.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class CommonLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@Value("${spring.security.loginType}")
	private String loginType;
	@Resource
	private ObjectMapper objectMapper;


	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
										HttpServletResponse response,
										AuthenticationException exception) throws IOException, ServletException {
		log.warn("认证失败");
		String error = "认证失败";
		if (exception instanceof SessionAuthenticationException) {
			error = exception.getMessage();
		}
		if ("JSON".equalsIgnoreCase(loginType)) {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(
					objectMapper.writeValueAsString(
							Result.error().code(400).message(error)
					)
			);
		} else {
			response.setContentType("text/html;charset=utf-8");
			//返回登录页面
			super.onAuthenticationFailure(request, response, exception);
		}
	}

}
